<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="主体名称">
        <el-input v-model="queryParams.companyName" placeholder="请输入主体名称" clearable />
      </el-form-item>
      <el-form-item label="注册手机号">
        <el-input v-model="queryParams.mobilePhone" placeholder="请输入注册手机号" clearable />
      </el-form-item>
      <el-form-item label="是否会员">
        <el-select v-model="queryParams.memberFlag" placeholder="请选择是否会员" clearable>
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态">
        <el-select v-model="queryParams.userStatus" placeholder="请选择用户状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="冻结" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="table"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="companyName" label="主体名称" />
      <el-table-column prop="mobilePhone" label="注册手机号" />
      <el-table-column prop="registerTime" label="注册时间" />
      <el-table-column label="营业执照" align="center">
        <template>
          <image-preview
            src="https://ts1.tc.mm.bing.net/th/id/R-C.987f582c510be58755c4933cda68d525?rik=C0D21hJDYvXosw&riu=http%3a%2f%2fimg.pconline.com.cn%2fimages%2fupload%2fupc%2ftx%2fwallpaper%2f1305%2f16%2fc4%2f20990657_1368686545122.jpg&ehk=netN2qzcCVS4ALUQfDOwxAwFcy41oxC%2b0xTFvOYy5ds%3d&risl=&pid=ImgRaw&r=0"

          width="50" height="80" />
        </template>
      </el-table-column>
      <el-table-column prop="memberFlag" label="是否会员">
        <template #default="{ row }">
          <el-tag :type="row.memberFlag === 1 ? 'success' : 'info'">{{ row.memberFlag === 1 ? '会员' : '非会员' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="perfectFlag" label="信息是否完善">
        <template #default="{ row }">
          <el-tag :type="row.perfectFlag === 1 ? 'success' : 'warning'">{{ row.perfectFlag === 1 ? '已完善' : '未完善' }}</el-tag>
<!--          <dict-tag :options="dict.type.njt_perfect_flag" :value="scope.row.perfectFlag" />-->
        </template>
      </el-table-column>
      <el-table-column prop="userStatus" label="用户状态">
        <template #default="{ row }">
          <el-tag :type="row.userStatus === 1 ? 'success' : 'danger'">{{ row.userStatus === 1 ? '正常' : '冻结' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-dropdown trigger="click" @command="(command) => handleCommand(command, row)">
            <span class="el-dropdown-link">
              更多<i class="el-icon--right"></i>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{action: 'detail', row: row}">详情</el-dropdown-item>
                <el-dropdown-item :command="{action: 'delete', row: row}" :disabled="row.userStatus !== 1">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;"
    />

    <!-- 批量操作提示 -->
    <div v-if="selectedRows.length > 0" class="batch-operation">
      已选择 {{ selectedRows.length }} 条
      <el-button size="small" @click="clearSelection">清空</el-button>
      <el-button size="small" type="danger" @click="handleDeleteBatch">批量删除</el-button>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editForm">
        <el-form-item label="主体名称" prop="companyName">
          <el-input v-model="editForm.companyName" placeholder="请输入主体名称" />
        </el-form-item>

        <el-form-item label="注册手机号" prop="mobilePhone">
          <el-input v-model="editForm.mobilePhone" placeholder="请输入注册手机号" />
        </el-form-item>

        <el-form-item label="注册时间" prop="registerTime">
          <el-date-picker
            v-model="editForm.registerTime"
            type="datetime"
            placeholder="请选择注册时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="是否会员" prop="memberFlag">
          <el-select v-model="editForm.memberFlag" placeholder="请选择是否会员" style="width: 100%">
            <el-option label="会员" :value="1" />
            <el-option label="非会员" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item label="用户状态" prop="userStatus">
          <el-select v-model="editForm.userStatus" placeholder="请选择用户状态" style="width: 100%">
            <el-option label="正常" :value="1" />
            <el-option label="冻结" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm" :loading="editLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNjtUserRegister, updateNjtUserRegister, delNjtUserRegister, exportNjtUserRegister } from "@/api/njt/user/register";
import { download } from "@/utils/request";
import dict from "@/utils/dict";

export default {
  name: "Index",
  dicts:['njt_member_flag','njt_perfect_flag','njt_userStatus_flag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 编辑按钮loading
      editLoading: false,
      // 查询参数
      queryParams: {
        companyName: "",
        mobilePhone: "",
        memberFlag: undefined,
        userStatus: undefined,
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      total: 0,
      selectedRows: [],

      // 编辑弹窗相关数据
      editDialogVisible: false,
      editForm: {
        id: null,
        companyName: '',
        mobilePhone: '',
        registerTime: '',
        memberFlag: 0,
        userStatus: 1
      },
      editRules: {
        companyName: [
          { required: true, message: '主体名称不能为空', trigger: 'blur' }
        ],
        mobilePhone: [
          { required: true, message: '注册手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        memberFlag: [
          { required: true, message: '请选择是否会员', trigger: 'change' }
        ],
        userStatus: [
          { required: true, message: '请选择用户状态', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    dict,
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listNjtUserRegister(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetForm() {
      this.queryParams = {
        companyName: "",
        mobilePhone: "",
        memberFlag: undefined,
        userStatus: undefined,
        pageNum: 1,
        pageSize: 10
      };
      this.getList();
    },
    exportData() {
      this.download('/nongjt/userRegister/export',
        {...this.queryParams},
        `user_${new Date().getTime()}.xlsx`)
            },
    handleEdit(row) {
      // 设置编辑表单数据
      this.editForm = {
        id: row.id,
        companyName: row.companyName,
        mobilePhone: row.mobilePhone,
        registerTime: row.registerTime,
        memberFlag: row.memberFlag,
        userStatus: row.userStatus
      };
      // 显示编辑弹窗
      this.editDialogVisible = true;
    },
    handleCommand(command) {
      const {action, row} = command;
      if (action === 'detail') {
        this.$modal.msgSuccess("查看详情，用户ID: " + row.id);
      } else if (action === 'delete') {
        this.handleDelete(row);
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm("确定要删除用户'" + row.companyName + "'吗？").then(() => {
        return delNjtUserRegister(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 批量删除按钮操作 */
    handleDeleteBatch() {
      const ids = this.selectedRows.map(item => item.id);
      this.$modal.confirm("确定要删除这 " + ids.length + " 个用户吗？").then(() => {
        return delNjtUserRegister(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.clearSelection();
      }).catch(() => {});
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    clearSelection() {
      this.$refs.table.clearSelection();
      this.selectedRows = [];
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 提交编辑表单
    submitEditForm() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.editLoading = true;
          updateNjtUserRegister(this.editForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.editDialogVisible = false;
            this.getList();
          }).finally(() => {
            this.editLoading = false;
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.batch-operation {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  margin-left: 10px;
}
</style>
